package cn.yunhe.action;

import cn.yunhe.dao.EmpDao;
import cn.yunhe.entity.Emp;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.components.ActionError;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;
@Controller
@Scope(value="prototype")
@ParentPackage("json-default")
public class HelloAction extends BaseAction implements ModelDriven<Object> {
    @Resource
    private EmpDao dao;
    private Emp emp=new Emp();
    private List<Emp> list;
    private  List<Emp> emp1;

    public String findById(){
        emp = dao.findById(emp.getId());
        return SUCCESS;
    }
    @Action(value = "login",results = {
            //chain 是action 之间的跳转  默认的是页面的跳转
            @Result(type="chain" ,location = "search"),
            @Result(name="error",location = "/login.jsp")

    })
    public String login(){
        if(dao.login(emp.getEname(),emp.getJob())){
            return  SUCCESS;
        }else{
            this.addFieldError("error","登录失败，请重新登录");
            return  ERROR;
        }

    }
    @Action(value="search",results = {
            @Result(location = "/search.jsp")
    })
    public  String getAll(){
        list = dao.findAll();
 getMapRequest().put("list",list);
        return  SUCCESS;
    }
    public String  update(){
        dao.update(emp);
        return  SUCCESS;
    }
    @Action(value = "delete",results = {
            @Result( type="chain" ,location = "search")
    })
    public  String delete(){
        dao.delete(emp);
        return SUCCESS;
    }
    @Action(value = "register",results = {
            @Result(location = "/login.jsp")
    })
    public  String add(){

        dao.add(emp);
        return  SUCCESS;
    }
    @Action(value = "searchs",results = {
            @Result(location = "/search.jsp"),
            @Result( name ="error",location = "/search.jsp")
    })
    public  String ByKeword(){
        List<Emp> list = dao.find(emp.getKeyword());
        if(list.size()>0){
            getMapRequest().put("list",list);

            return  SUCCESS;
        }else {
             this.addFieldError("error","查无结果，请重新搜索");
             return ERROR;
        }


    }




    public Emp getModel(){
        return  emp;
    }
}
